package repostiroy

import (
	"gorm.io/gorm"
	"shyxy-net/common/cache/lru"
	"shyxy-net/common/db/model-service/model"
)

type RpcServerInfoRepository interface {
	FindRpcServerInfosByModelName(modelName string) ([]*model.RpcServerInfo, error)
}

type rpcServerInfoRepository struct {
	db *gorm.DB
}

func NewCachedRpcServerInfoRepository(db *gorm.DB, cache *lru.LRU) RpcServerInfoRepository {
	dbRepo := NewRpcServerRepository(db)
	return newCachedRpcServerRepository(dbRepo, cache)
}
func NewRpcServerRepository(db *gorm.DB) RpcServerInfoRepository {
	return &rpcServerInfoRepository{
		db: db,
	}
}

func (r *rpcServerInfoRepository) FindRpcServerInfosByModelName(modelName string) ([]*model.RpcServerInfo, error) {
	var rpcServerInfos []*model.RpcServerInfo
	return rpcServerInfos, r.db.Where("model_name = ?", modelName).Find(&rpcServerInfos).Error
}

type cachedRpcServerRepository struct {
	repo RpcServerInfoRepository
	lru  *lru.LRU
}

func newCachedRpcServerRepository(repo RpcServerInfoRepository, cache *lru.LRU) RpcServerInfoRepository {
	return &cachedRpcServerRepository{
		repo: repo,
		lru:  cache,
	}
}
func (c *cachedRpcServerRepository) FindRpcServerInfosByModelName(modelName string) ([]*model.RpcServerInfo, error) {
	if cached, ok := c.lru.Get(modelName); ok {
		return cached.([]*model.RpcServerInfo), nil
	}

	rpcServers, err := c.repo.FindRpcServerInfosByModelName(modelName)
	if err != nil {
		return nil, err
	}

	c.lru.Add(modelName, rpcServers)
	return rpcServers, nil
}
